package org.wxd.bi.test;

import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wxd.lang.RunResult;
import org.wxd.net.ssl.SslProtocolType;
import org.wxd.net.web.hs.util.HttpPost;
import org.wxd.str.StringUtil;
import org.wxd.str.json.Json2Object;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @author: Troy.Chen(無心道, 15388152619)
 * @version: 2021-09-30 18:21
 **/
public class Query implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(Query.class);


    @Test
    public void queryAllTable() {
        String bodyString = HttpPost.of("https://127.0.0.1:18601/query/dataMapping")
                .setSslProtocolType(SslProtocolType.TLSV12)
                .request()
                .bodyString();
        log.debug(bodyString);
    }

    @Test
    public void queryTable() {
        String bodyString = HttpPost.of("https://127.0.0.1:18601/query/data")
                .setSslProtocolType(SslProtocolType.TLSV12)
                .addTextParam("tableName", "loginlog")
                .request()
                .bodyString();
        RunResult runResult = Json2Object.parseObject(bodyString, RunResult.class);
        JSONObject resultData = runResult.JSONObject();
        String tableInfo = resultData.getString("tableInfo");
        Map<String, String> columnInfo = (Map<String, String>) resultData.get("columnInfo");
        StringBuilder builder = new StringBuilder();
        builder.append("\n");
        builder.append("tableInfo：").append(tableInfo).append("\n");
        builder.append("--------------------------------------------------------------------------------------------------------").append("\n");
        builder.append("|");
        for (Map.Entry<String, String> entry : columnInfo.entrySet()) {
            builder.append(StringUtil.padRight(entry.getValue(), 21, ' ')).append("|");
        }
        builder.append("\n");

        List<String> data = (List<String>) resultData.get("rows");
        for (String datum : data) {
            builder.append("|");
            JSONObject row = JSONObject.parseObject(datum);
            for (String key : columnInfo.keySet()) {
                String o = row.getString(key);
                builder.append(StringUtil.padRight(o, 21, ' ')).append("|");
            }
            builder.append("\n");
        }
        log.debug(builder.toString());

    }
}
